package com.example.mybaiduweishi.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.NotificationCompat;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;


import com.example.mybaiduweishi.MyApplication;
import com.example.mybaiduweishi.R;
import com.example.mybaiduweishi.com.Constants;
import com.example.mybaiduweishi.db.AddressDao;
import com.example.mybaiduweishi.db.MobileInfoDao;
import com.example.mybaiduweishi.vo.Contacts;
import com.example.mybaiduweishi.vo.MobileInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import retrofit2.http.Url;

import static android.content.Context.NOTIFICATION_SERVICE;
import static com.zhy.http.okhttp.log.LoggerInterceptor.TAG;

/**
 * Created by admin on 2017/5/10.
 */
//普通JAVA类，是没有上下文
public class MyUtil {

    static NotificationManager    notificationManager;
    static NotificationCompat.Builder    notificationBuild;

    //返回共享首选项对象
    public static SharedPreferences getSharedPre(){
        //获取上下文  再获取共享首选项
        return  MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);
    }
    //判断是否有SD卡
    public static boolean isSDCard(){
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state)){
            return true;
        }else{
            return false;
        }
    }

    //能否读写 能写就写入SD卡，不能就写手机存储中
    public static File getPath(){
        File path = null;
        if(isSDCard()){
            path = Environment.getExternalStorageDirectory();
        }else{
            path = Environment.getDownloadCacheDirectory();
        }

        return path;
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {

        try {
            PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static Drawable getBBXIcon(String icon){
        Context context = MyApplication.getContext();
        int resId = context.getResources().getIdentifier(icon,"drawable",context.getPackageName());
        Drawable drawable = ContextCompat.getDrawable(context,resId);
        return drawable;
    }

    //复制文件
    public static void copyFileToMobile(Context context ,String fromdbname,String todbname) throws IOException {
        //源文件地址
        URL url = context.getClass().getClassLoader().getResource("assets/"+fromdbname);
        String dbfile = "/data/data/"+MyApplication.getContext().getPackageName()+"/databases";
        File dbfileMobile = new File(dbfile);
        if (!dbfileMobile.exists()){
            dbfileMobile.mkdirs();
        }
        File filetext = new File(dbfileMobile+"/"+fromdbname);
        if (!dbfileMobile.exists()){
            dbfileMobile.createNewFile();//文件
        }
        /**
         * url:包含路径的源文件
         * filetext:目的地包含路径的文件
         */
        FileUtils.copyURLToFile(url,filetext);
    }


    /**
     * 得到联系人信息
     * name tel address
     * @return
     */
    public static List<Contacts> getAllContacts() {
        //承载数据
        List<Contacts> lists = new ArrayList<Contacts>();
        //从内容提供者获得查询的方法
        ContentResolver resolver = MyApplication.getContext().getContentResolver();
        //查询联系人uri
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);

        if (cursor != null) {
            while (cursor.moveToNext()){
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                int num = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String telphone = null;
                String address = null;
                if (num > 0){ //查询中有号码
                    telphone = getPhonenumById(id);
                }
//                //归属地
//                String address = AddressDao.queryAdress(telphone,MyApplication.getContext());
//                Contacts contacts = new Contacts(id,name,telphone,address);
//                lists.add(contacts);
                address=getAddressByTel(telphone);
                Contacts contacts = new Contacts(id,name,telphone,address);
                lists.add(contacts);
            }
            cursor.close();
        }
        return lists;
    }

    public static String getPhonenumById(int id) {
        String telnum = null;//电话号码
        ContentResolver cr = MyApplication.getContext().getContentResolver();
        Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? ",
                new String[] {id+""},null);
        if (cursor != null){
            if (cursor.moveToNext()) {
                telnum = cursor.getString(cursor.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        cursor.close();
        return telnum;
    }

    public static String getAddressByTel(String tel){
        String address = null;
        String newtel =  tel.replace(" ","").replace("-","");
        String telnum = null;
        if (newtel.length() == 11 && newtel.matches("1[34578]\\d{9}$")){
            telnum = newtel.substring(0,7);
            address = getMobileAddreByTel(telnum);
        }else {
            int lenth = newtel.length();
            //对特殊电话做处理
            switch (lenth){
                case 10:
                    address = getZuojiAddressBYTel(newtel,3);
                    break;
                case 11:
                    address = getZuojiAddressBYTel(newtel,3);
                    if (address == null){
                        address = getZuojiAddressBYTel(newtel,4);
                    }
                    break;
                case 12:
                    address  = getZuojiAddressBYTel(newtel,4);
                    break;
                default:
                    address = "未知";
                    break;
            }
        }

        return address;
    }

//    private static void gettelPhone(String telnum,String newtel) {
//        telnum =newtel.substring(0,7);
//        MobileInfo mobileInfo= MyApplication.getMobiledaoSession()
//                .getMobileInfoDao()
//                .queryBuilder()
//                .where(MobileInfoDao.Properties.MobileNumber.eq(telnum))
//                .distinct()
//                .unique();
//    }

    private static String getZuojiAddressBYTel(String newtel, int i) {
        MobileInfo mobile = MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,i)))
                .limit(1)
                .distinct()
                .unique();
        return mobile.getMobileArea();
    }

    public static String getMobileAddreByTel(String tel){
        MobileInfo mobile = MyApplication.getMobiledaoSession()
                .getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel))
                .limit(1)
                .distinct()
                .unique();
        return mobile.getMobileArea();
    }

    //发送短信
    public static void sendSMS(String number,String message){
        SmsManager smsManager = SmsManager.getDefault();
        List<String> listsms = smsManager.divideMessage(message);
        for (String text : listsms) {
            smsManager.sendTextMessage("",null,text,null,null);
        }
    }

}
